using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;

using KNCApp.Business.Models;
using KNCApp.Business.Interfaces;
using KNCApp.DataSource;

namespace KNCApp.Port
{
    public class ResUIDataHandler : IDataHandler
    {
        private Queue<AbstractObj> resultsQueue;
        private Thread addResThread;
        private bool isRunning = false;
        private UpdateDataDelegate updater;
        
        public ResUIDataHandler(UpdateDataDelegate up)
        {
            updater = up;
        }

        public void HandleData(AbstractObj obj)
        {
            if (obj != null)
            {
                lock (resultsQueue)
                {
                    resultsQueue.Enqueue(obj);
                    Monitor.PulseAll(resultsQueue);
                }
            }
        }

        private void updateUI()
        {
            AbstractObj aObj = null;
            while (isRunning)
            {
                lock (resultsQueue)
                {
                    if (resultsQueue.Count == 0)
                    {
                        Monitor.Wait(resultsQueue);
                    }
                    if(resultsQueue.Count != 0)
                        aObj = resultsQueue.Dequeue();
                }
                if(updater != null)
                   Util.InvocationHelper.Invoke(updater, aObj);
            }
        }

        public void Start()
        {
            resultsQueue = new Queue<AbstractObj>();
            addResThread = new Thread(updateUI);
            isRunning = true;
            addResThread.Start();
        }

        public void Stop()
        {
            isRunning = false;
            lock (resultsQueue)
            {
                Monitor.PulseAll(resultsQueue);
            }
        }

    }
}
